<template>
  <div>
    <i-dialog
      :title="'迁移设备'"
      :visible="visible"
      width="642px"
      :close-on-click-modal="false"
      @close="outerClose"
    >
      <i-form
        :items="formItems"
        :model="form"
        ref="form"
        label-width="95px"
        class="demo-form"
      >
      </i-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="outerClose">取 消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </span>
    </i-dialog>
  </div>
</template>
<script>
import { listTransferStation, transferDevice } from '@/api/device'
export default {
  name: 'MigrateDevice',
  data() {
    return {
      form: {},
      formItems: [
        {
          type: 'select',
          value: 'newStationId',
          label: '充电站名称',
          placeholder: '请选择充电站',
          clearable: true,
          required: true,
        },
      ],
    }
  },
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    deviceAttr: {
      type: Object,
      default: () => {},
    },
  },
  created() {
    listTransferStation().then((res) => {
      let index = this.formItems.findIndex(
        (item) => item.value === 'newStationId'
      )
      if (index < 0) return
      let item = this.formItems[index]
      item.options = res.map((item) => {
        return {
          label: item.stationName,
          value: item.id,
        }
      })
      this.$set(this.formItems, index, item)
    })
  },
  methods: {
    outerClose() {
      this.$emit('update:visible', false)
    },
    refreshTable() {
      this.$emit('refreshTable')
    },
    submit() {
      let params = {
        deviceId: this.deviceAttr.deviceId,
        ...this.form,
      }
      console.log(this.deviceAttr.deviceId)
      console.log(this.form.newStationId)
      console.log(this.deviceAttr.deviceId === this.form.newStationId)
      if (this.deviceAttr.deviceId === this.form.newStationId) {
        this.$message({
          message: '这是同一个充电站',
          type: 'warning',
        })
        return
      }
      transferDevice(params).then(
        () => {
          this.$message({
            message: '设备迁移成功',
            type: 'success',
          })

          this.refreshTable()
          this.outerClose()
        },
        () => {
          this.refreshTable()
          this.outerClose()
        }
      )
    },
  },
}
</script>
<style lang="scss" scoped>
.alloc-role {
  &::v-deep .table-wrapper {
    height: 500px;
    overflow: auto;
  }
}
</style>
